# -*- coding: utf-8 -*-
"""
阿里云百炼Embedding模型使用示例
展示如何将OpenAI应用迁移至阿里云百炼，只需调整三个参数：
- base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
- api_key: 阿里云百炼API Key
- model: text-embedding-v4 或 text-embedding-v3
"""

import os
import sys
from typing import List
import numpy as np

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(os.path.dirname(current_dir))
sys.path.append(project_root)

from config_reader import get_dashscope_config, get_embedder_config
from dashscope_embedding_openai_compatible import DashScopeEmbedding


def example_1_basic_usage():
    """
    示例1：基本用法 - 单个文本嵌入
    """
    print("=== 示例1：基本用法 - 单个文本嵌入 ===")
    
    try:
        # 创建DashScope Embedding实例
        embedding = DashScopeEmbedding(
            model="text-embedding-v4",
            dimensions=1024
        )
        
        # 示例文本
        text = "阿里云百炼是阿里云推出的大模型服务平台"
        
        # 获取嵌入向量
        vector = embedding.get_embedding(text)
        
        print(f"输入文本: {text}")
        print(f"嵌入向量维度: {len(vector)}")
        print(f"嵌入向量前5个值: {vector[:5]}")
        print(f"嵌入向量后5个值: {vector[-5:]}")
        
    except Exception as e:
        print(f"示例1执行失败: {e}")


def example_2_batch_embedding():
    """
    示例2：批量文本嵌入
    """
    print("\n=== 示例2：批量文本嵌入 ===")
    
    try:
        # 创建DashScope Embedding实例
        embedding = DashScopeEmbedding(
            model="text-embedding-v4",
            dimensions=1024
        )
        
        # 示例文本列表
        texts = [
            "人工智能正在改变世界",
            "机器学习是AI的核心技术",
            "深度学习推动了AI的发展",
            "自然语言处理让机器理解人类语言",
            "计算机视觉让机器看懂世界"
        ]
        
        # 批量获取嵌入向量
        vectors = embedding.get_embeddings(texts)
        
        print(f"批量处理了 {len(texts)} 个文本")
        print(f"每个嵌入向量维度: {len(vectors[0])}")
        
        # 显示每个文本的嵌入向量信息
        for i, (text, vector) in enumerate(zip(texts, vectors)):
            print(f"  {i+1}. {text[:20]}... -> 向量维度: {len(vector)}")
        
    except Exception as e:
        print(f"示例2执行失败: {e}")


def example_3_similarity_search():
    """
    示例3：相似度搜索
    """
    print("\n=== 示例3：相似度搜索 ===")
    
    try:
        # 创建DashScope Embedding实例
        embedding = DashScopeEmbedding(
            model="text-embedding-v4",
            dimensions=1024
        )
        
        # 候选文本
        candidate_texts = [
            "狗是伟大的伴侣，以其忠诚和友好而闻名。",
            "猫是独立的宠物，通常喜欢自己的空间。",
            "金鱼是初学者的流行宠物，需要相对简单的护理。",
            "鹦鹉是聪明的鸟类，能够模仿人类的语言。",
            "兔子是社交动物，需要足够的空间跳跃。",
            "人工智能正在改变世界。",
            "机器学习是AI的核心技术。",
            "深度学习推动了AI的发展。"
        ]
        
        # 查询文本
        query = "咖啡猫"
        
        # 执行相似度搜索
        results = embedding.similarity_search(query, candidate_texts, top_k=3)
        
        print(f"查询: {query}")
        print("最相似的文本:")
        for i, (text, similarity) in enumerate(results, 1):
            print(f"  {i}. 相似度: {similarity:.4f} - {text}")
        
    except Exception as e:
        print(f"示例3执行失败: {e}")


def example_4_cosine_similarity():
    """
    示例4：余弦相似度计算
    """
    print("\n=== 示例4：余弦相似度计算 ===")
    
    try:
        # 创建DashScope Embedding实例
        embedding = DashScopeEmbedding(
            model="text-embedding-v4",
            dimensions=1024
        )
        
        # 示例文本对
        text_pairs = [
            ("人工智能", "AI技术"),
            ("机器学习", "深度学习"),
            ("猫", "狗"),
            ("苹果", "香蕉"),
            ("汽车", "飞机")
        ]
        
        print("文本对相似度分析:")
        for text1, text2 in text_pairs:
            # 获取两个文本的嵌入向量
            vec1 = embedding.get_embedding(text1)
            vec2 = embedding.get_embedding(text2)
            
            # 计算余弦相似度
            similarity = embedding.cosine_similarity(vec1, vec2)
            
            print(f"  '{text1}' vs '{text2}': {similarity:.4f}")
        
    except Exception as e:
        print(f"示例4执行失败: {e}")


def example_5_langchain_integration():
    """
    示例5：LangChain集成
    """
    print("\n=== 示例5：LangChain集成 ===")
    
    try:
        from langchain_openai import OpenAIEmbeddings
        from langchain_community.vectorstores import Chroma
        from langchain_core.documents import Document
        
        # 获取配置
        dashscope_config = get_dashscope_config()
        embedder_config = get_embedder_config()
        
        # 创建LangChain OpenAIEmbeddings实例（使用阿里云百炼）
        embeddings = OpenAIEmbeddings(
            openai_api_key=dashscope_config['api_key'],
            openai_api_base=dashscope_config['base_url'],
            model=embedder_config['model']
        )
        
        # 准备文档
        documents = [
            Document(page_content="阿里云百炼是阿里云推出的大模型服务平台", metadata={"source": "阿里云文档"}),
            Document(page_content="DashScope是阿里云百炼的核心服务", metadata={"source": "技术文档"}),
            Document(page_content="text-embedding-v4是阿里云百炼的嵌入模型", metadata={"source": "模型文档"}),
            Document(page_content="OpenAI接口兼容让迁移更简单", metadata={"source": "迁移指南"})
        ]
        
        # 创建向量存储
        vector_store = Chroma.from_documents(documents, embedding=embeddings)
        
        # 执行相似度搜索
        query = "什么是阿里云百炼？"
        results = vector_store.similarity_search_with_score(query, k=2)
        
        print(f"查询: {query}")
        print("搜索结果:")
        for i, (doc, score) in enumerate(results, 1):
            print(f"  {i}. 相似度: {score:.4f}")
            print(f"     内容: {doc.page_content}")
            print(f"     来源: {doc.metadata['source']}")
        
    except Exception as e:
        print(f"示例5执行失败: {e}")


def example_6_migration_from_openai():
    """
    示例6：从OpenAI迁移到阿里云百炼
    """
    print("\n=== 示例6：从OpenAI迁移到阿里云百炼 ===")
    
    print("迁移步骤:")
    print("1. 修改base_url:")
    print("   原: https://api.openai.com/v1")
    print("   新: https://dashscope.aliyuncs.com/compatible-mode/v1")
    print()
    
    print("2. 修改api_key:")
    print("   原: sk-proj-xxx (OpenAI API Key)")
    print("   新: sk-xxx (阿里云百炼API Key)")
    print()
    
    print("3. 修改model:")
    print("   原: text-embedding-ada-002")
    print("   新: text-embedding-v4 或 text-embedding-v3")
    print()
    
    print("4. 可选参数:")
    print("   - dimensions: 指定向量维度 (1024, 768, 512等)")
    print("   - encoding_format: 编码格式 (float)")
    print()
    
    # 展示迁移前后的代码对比
    print("代码迁移示例:")
    print("迁移前 (OpenAI):")
    print("""
from openai import OpenAI

client = OpenAI(api_key="sk-proj-xxx")
response = client.embeddings.create(
    input="Hello, world!",
    model="text-embedding-ada-002"
)
""")
    
    print("迁移后 (阿里云百炼):")
    print("""
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxx",  # 阿里云百炼API Key
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
response = client.embeddings.create(
    input="Hello, world!",
    model="text-embedding-v4",  # 阿里云百炼模型
    dimensions=1024,  # 可选：指定向量维度
    encoding_format="float"  # 可选：编码格式
)
""")


def main():
    """
    主函数 - 运行所有示例
    """
    print("阿里云百炼Embedding模型使用示例")
    print("=" * 50)
    
    # 检查配置
    try:
        dashscope_config = get_dashscope_config()
        print(f"✅ 配置检查通过")
        print(f"   API Key: {dashscope_config['api_key'][:10]}...")
        print(f"   Base URL: {dashscope_config['base_url']}")
        print()
    except Exception as e:
        print(f"❌ 配置检查失败: {e}")
        print("请确保在config.ini中正确配置了DASHSCOPE_API_KEY")
        return
    
    # 运行示例
    example_1_basic_usage()
    example_2_batch_embedding()
    example_3_similarity_search()
    example_4_cosine_similarity()
    example_5_langchain_integration()
    example_6_migration_from_openai()
    
    print("\n" + "=" * 50)
    print("所有示例执行完成！")


if __name__ == "__main__":
    main()

